package com.restaurantpicker;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.webkit.WebView;
import android.widget.Toast;

import com.restaurantpicker.model.Place;
import com.restaurantpicker.util.GPSTracker;
import com.restaurantpicker.util.GooglePlacesApiService;
import com.restaurantpicker.util.PickerUtility;

public class RestaurantePickerActivity extends Activity {
	private WebView webView;
	private GPSTracker gps;
	private ArrayList<Place> places = new ArrayList<Place>();
	private String keyword = "";
	private static final String HTML_ROOT = "file:///android_asset/pages/";
	private static final String JAVASCRIPT = "javascript:";
	private static final String BRC_OPEN = "('";
	private static final String BRC_CLOSE = "')";
	private JavaScriptInterface jsInt;


    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        jsInt = new JavaScriptInterface(this);
        
        setContentView(R.layout.my);
        webView = (WebView) findViewById(R.id.webview);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.addJavascriptInterface(jsInt, "pickerSupport"); 
        webView.loadUrl(HTML_ROOT + "index.html");
    }
    
    public class JavaScriptInterface{
        Context mContext;
 
        /** Instantiate the interface and set the context */
        JavaScriptInterface(Context c) {
            mContext = c;
        }
        
        public void alert(String toast) {
        	Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
        }          
        
        public void searchRestaurants(String toast, String callback) {
        	String json = "";
        	if(places!=null && places.size()>0 && keyword.equals(toast)){
        		json = PickerUtility.getAllRestJSON(places);
        	}else{
	        	gps = new GPSTracker(mContext);
	            // check if GPS enabled     
	            if(gps.canGetLocation()){
	                double latitude = gps.getLatitude();
	                double longitude = gps.getLongitude();
	                try{
	                	GooglePlacesApiService googlePlacesApi = new GooglePlacesApiService(mContext);
	                	places = googlePlacesApi.search(toast, latitude, longitude, 500);
	                	json = PickerUtility.getAllRestJSON(places);
	                    
	                    //\n is for new line
	                	if(toast !=null && toast.equals("any"))
	                		Toast.makeText(mContext, places.size()+" Restaurants where find it", Toast.LENGTH_LONG).show();
	                	else
	                		Toast.makeText(mContext, places.size()+" Restaurants of "+toast+" where find it", Toast.LENGTH_LONG).show();
	                }catch (Exception e) {
	                	Toast.makeText(mContext, e.toString(), Toast.LENGTH_LONG).show();
	                }
	            }else{
	                //can't get location
	                //GPS or Network is not enabled
	                //Ask user to enable GPS/network in settings
	                gps.showSettingsAlert();
	            }
        	}
        	keyword = toast;
        	final String callbackFunction = JAVASCRIPT + callback + BRC_OPEN + json + BRC_CLOSE;
        	loadURL(callbackFunction); 	            
        }  
        
        public void showDetailsRest(String restId, String callback){
        	
            double latitude = 0.0;
            double longitude = 0.0;        	
        	
        	gps = new GPSTracker(mContext);
        	
            if(gps.canGetLocation()){
                latitude = gps.getLatitude();
                longitude = gps.getLongitude();
            }else{
                gps.showSettingsAlert();
            }        	
        	
        	String json = "";
        	Place rest = new Place();
        	for(Place place : places){
        		if (place.id.equals(restId)){
        			rest = place;
        			break;
        		}
        	}
        	rest.myLatitude = String.valueOf(latitude);
        	rest.myLongitude = String.valueOf(longitude);
        	json = PickerUtility.getRestJSON(rest);
        	final String callbackFunction = JAVASCRIPT + callback + BRC_OPEN + json + BRC_CLOSE;
        	loadURL(callbackFunction); 	            
        }
        
        public String getPhone(String reference){
        	GooglePlacesApiService googlePlacesApi = new GooglePlacesApiService(mContext);
        	return googlePlacesApi.getPhone(reference);
        }        
        
        public void loadPage(String in){    	
        	webView.loadUrl(HTML_ROOT + in);
        }
        
        private void loadURL(String in){    	
        	webView.loadUrl(in);
        }        
    }
    
    public boolean onCreateOptionsMenu(Menu menu){

    	MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);

    	return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case R.id.exit:
            	System.exit(0);
                return true;
            case R.id.nsearch:
            	places = new ArrayList<Place>();
            	jsInt.loadPage("index.html");
                return true;                
            default:
                return super.onOptionsItemSelected(item);
        }
    }     
 
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // Check if the key event was the BACK key and if there's history
        if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
        	webView.goBack();
            return true;
        }
        // If it wasn't the BACK key or there's no web page history, bubble up to the default
        // system behavior (probably exit the activity)
        return super.onKeyDown(keyCode, event);
    }
}